package com.foreknow.service.impl;

import com.foreknow.bean.Guestbook;
import com.foreknow.dao.impl.AdminDaoImpl;
import com.foreknow.dao.impl.GuestbookDaoImpl;
import com.foreknow.db.DBManager;
import com.foreknow.service.GuestbookService;
import com.foreknow.util.Pagination;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;

public class GuestbookServiceImpl implements GuestbookService {
    @Override
    public boolean save(Guestbook gb) {
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        GuestbookDaoImpl guestbookDao = new GuestbookDaoImpl();
        //将DBManager中获取到的conn传递给JdbcTemplate中的conn
        guestbookDao.setConnection(conn);
        boolean isRight = false;
        try {
            isRight=guestbookDao.addGuestbook(gb);
            conn.commit();
        } catch (SQLException throwables) {
            try {
                conn.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            throwables.printStackTrace();

        }

        return isRight;
    }

    @Override
    public List<Object> queyrInfo() {
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        GuestbookDaoImpl guestbookDao = new GuestbookDaoImpl();
        //将GBManager中获取到的conn传递给JdbcTemplate中的conn
        guestbookDao.setConnection(conn);
        List<Object> list = null;
        try {
            list = guestbookDao.queryAll();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list;
    }

    @Override
    public boolean delInfo(int id) {
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        GuestbookDaoImpl guestbookDao = new GuestbookDaoImpl();
        //将GBManager中获取到的conn传递给JdbcTemplate中的conn
        guestbookDao.setConnection(conn);
        boolean isRight=false;

        try {
            isRight = guestbookDao.delete(id);
            conn.commit();
        } catch (SQLException throwables) {
            try {
                conn.rollback();
            } catch (SQLException e) {
                e.printStackTrace();
            }
            throwables.printStackTrace();
        }
        return isRight;
    }

    @Override
    public Pagination getByPage(int pageSize, int pageNumber) {
        DBManager dbManager = DBManager.getInstance();
        Connection conn = dbManager.getConnection();
        GuestbookDaoImpl guestbookDao = new GuestbookDaoImpl();
        //将GBManager中获取到的conn传递给JdbcTemplate中的conn
        guestbookDao.setConnection(conn);
        Pagination pagination = null;
        pagination = guestbookDao.getGuestbookByPage(pageSize,pageNumber);
        return pagination;
    }
}
